package com.guli.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.guli.utils.R;
import com.guli.vod.service.VideoUploadService;
import com.guli.vod.utils.ConstantPropertiesUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author ZHAOZHENYU
 * @since 2022/9/29
 */

//@CrossOrigin
@Api(description="阿里云视频点播微服务")
@RestController
@RequestMapping("/vod/video")
public class VideoUploadController {

    @Autowired
    private VideoUploadService videoUploadService;

    @PostMapping("/upload")
    public R upload(@RequestBody MultipartFile file){
        String videoId = videoUploadService.uploadVideo(file);
        return R.ok().message("视频上传成功").data("videoId", videoId);
    }

    @DeleteMapping("/{videoId}")
    public R removeVideo(@PathVariable String videoId) throws InterruptedException {

        // 测试熔断器
        /*Thread.sleep(20000);
        if (true) {
            throw new GuliException(20001, "vod视频删除失败");
        }*/

        videoUploadService.removeVideo(videoId);
        return R.ok().message("vod视频删除成功");

    }

    @DeleteMapping("/deleteBatch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList){
        for (String videoId : videoIdList) {
            videoUploadService.removeVideo(videoId);
        }
        return R.ok().message("批量视频删除成功");
    }

    // 获取播放凭证
    @GetMapping("get-play-auth/{videoId}")
    public R getVideoPlayAuth(@PathVariable("videoId") String videoId) throws Exception {

        //获取阿里云存储相关常量
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        //初始化
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai",
                ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        //请求
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);

        //响应
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);

        //得到播放凭证
        String playAuth = response.getPlayAuth();

        //返回结果
        return R.ok().message("获取凭证成功").data("playAuth", playAuth);
    }

}
